package dev.bong.service.impl;

import dev.bong.mapper.LabMapper;
import dev.bong.mapper.LabRepairMapper;
import dev.bong.mapper.UserMapper;
import dev.bong.pojo.entity.LabRepair;
import dev.bong.service.ExperimentService;
import dev.bong.utils.ThreadLocalUtil;
import dev.bong.vo.RepairVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ExperimentServiceImpl implements ExperimentService {

    @Autowired
    private LabMapper labMapper;

    @Autowired
    private LabRepairMapper labRepairMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<RepairVo> getRepairList(Integer experimenterId) {
        List<Integer> labIds=labMapper.getIdsByExpId(experimenterId);
        Map<Integer,String> map=new HashMap<>();
        for(Integer labId:labIds){
            map.put(labId,labMapper.getLabNameById(labId));
        }
        List<LabRepair> list=labRepairMapper.selectByLabIds(labIds);

        List<RepairVo> ans=new ArrayList<>();

        for(LabRepair cur:list){
            String teacherName = userMapper.getNameById(cur.getTeacherId());
            String labName = map.get(cur.getLabId());
            RepairVo vo=RepairVo.builder()
                    .id(cur.getId())
                    .repairStatus(cur.getRepairStatus())
                    .labNumber(cur.getLabNumber())
                    .labName(labName)
                    .faultDescription(cur.getFaultDescription())
                    .teacherName(teacherName)
                    .repairStatus(cur.getRepairStatus())
                    .repairTime(cur.getRepairTime())
                    .repairSituation(cur.getRepairSituation())
                    .build();

            ans.add(vo);
        }
        return ans;




    }

    @Override
    public void startRepair(Integer repairId) {
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId= (Integer) map.get("userId");
        LocalDateTime  now=LocalDateTime.now();

        labRepairMapper.updateRepairStatus(repairId,0,userId,now);
    }

    @Override
    public void finishRepair(Integer repairId, String situation) {

        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId= (Integer) map.get("userId");
        LocalDateTime  now=LocalDateTime.now();
        labRepairMapper.updateRepairStatus(repairId,1,userId,now);
        labRepairMapper.updateRepairSituation(repairId,situation,userId,now);
    }
}
